package org.example.managere.controller.feibiao;

import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.example.managere.dto.feibiao.AmKnowledgeBasicDto;
import org.example.managere.service.feibiao.AmKnowledgeBasicService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;

/**
 * 电机基础知识控制器 - 电机向量知识库
 */
@RestController
@RequestMapping("/api/feibiao/knowledge/basic")
@RequiredArgsConstructor
public class AmKnowledgeBasicController {
    
    private final AmKnowledgeBasicService amKnowledgeBasicService;
    
    /**
     * 获取所有电机基础知识（分页）
     *
     * @param page 页码（从0开始）
     * @param size 每页大小
     * @param sort 排序字段
     * @return 电机基础知识分页结果
     */
    @GetMapping
    public ResponseEntity<Page<AmKnowledgeBasicDto>> getAllKnowledgeBasic(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false, defaultValue = "motor_id,asc") String sort) {
        Pageable pageable;
        if (sort != null && !sort.isEmpty()) {
            String[] sortParams = sort.split(",");
            String sortField = sortParams[0];
            Sort.Direction direction = (sortParams.length > 1 && sortParams[1].equalsIgnoreCase("desc"))
                    ? Sort.Direction.DESC : Sort.Direction.ASC;
            pageable = PageRequest.of(page, size, Sort.by(direction, sortField));
        } else {
            pageable = PageRequest.of(page, size);
        }
        return ResponseEntity.ok(amKnowledgeBasicService.findAll(pageable));
    }
    
    /**
     * 根据ID获取电机基础知识
     *
     * @param motorId 电机ID
     * @return 电机基础知识
     */
    @GetMapping("/{motorId}")
    public ResponseEntity<AmKnowledgeBasicDto> getKnowledgeBasicById(@PathVariable String motorId) {
        return amKnowledgeBasicService.findById(motorId)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }
    
    /**
     * 创建电机基础知识
     *
     * @param dto 电机基础知识DTO
     * @return 创建后的电机基础知识
     */
    @PostMapping
    public ResponseEntity<AmKnowledgeBasicDto> createKnowledgeBasic(@Valid @RequestBody AmKnowledgeBasicDto dto) {
        return new ResponseEntity<>(amKnowledgeBasicService.save(dto), HttpStatus.CREATED);
    }
    
    /**
     * 更新电机基础知识
     *
     * @param motorId 电机ID
     * @param dto     电机基础知识DTO
     * @return 更新后的电机基础知识
     */
    @PutMapping("/{motorId}")
    public ResponseEntity<AmKnowledgeBasicDto> updateKnowledgeBasic(
            @PathVariable String motorId,
            @Valid @RequestBody AmKnowledgeBasicDto dto) {
        if (!motorId.equals(dto.getMotorId())) {
            return ResponseEntity.badRequest().build();
        }
        return ResponseEntity.ok(amKnowledgeBasicService.update(dto));
    }
    
    /**
     * 删除电机基础知识
     *
     * @param motorId 电机ID
     * @return 无内容响应
     */
    @DeleteMapping("/{motorId}")
    public ResponseEntity<Void> deleteKnowledgeBasic(@PathVariable String motorId) {
        amKnowledgeBasicService.deleteById(motorId);
        return ResponseEntity.noContent().build();
    }
    
    /**
     * 搜索电机基础知识
     *
     * @param keyword  关键字
     * @param page     页码
     * @param size     每页大小
     * @param sort     排序字段
     * @return 符合条件的电机基础知识分页结果
     */
    @GetMapping("/search")
    public ResponseEntity<Page<AmKnowledgeBasicDto>> searchKnowledgeBasic(
            @RequestParam String keyword,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false, defaultValue = "motor_id,asc") String sort) {
        Pageable pageable;
        if (sort != null && !sort.isEmpty()) {
            String[] sortParams = sort.split(",");
            String sortField = sortParams[0];
            Sort.Direction direction = (sortParams.length > 1 && sortParams[1].equalsIgnoreCase("desc"))
                    ? Sort.Direction.DESC : Sort.Direction.ASC;
            pageable = PageRequest.of(page, size, Sort.by(direction, sortField));
        } else {
            pageable = PageRequest.of(page, size);
        }
        return ResponseEntity.ok(amKnowledgeBasicService.searchByKeyword(keyword, pageable));
    }
    
    /**
     * 根据电机型号查询
     *
     * @param motorType 电机型号
     * @return 符合条件的电机基础知识列表
     */
    @GetMapping("/by-type")
    public ResponseEntity<List<AmKnowledgeBasicDto>> findByMotorType(@RequestParam String motorType) {
        return ResponseEntity.ok(amKnowledgeBasicService.findByMotorType(motorType));
    }
    
    /**
     * 根据电机型号精确查询
     *
     * @param motorType 电机型号
     * @return 电机基础知识
     */
    @GetMapping("/exact-type")
    public ResponseEntity<AmKnowledgeBasicDto> findExactByMotorType(@RequestParam String motorType) {
        return amKnowledgeBasicService.findExactByMotorType(motorType)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }
    
    /**
     * 根据制造商查询
     *
     * @param manufacturer 制造商
     * @return 符合条件的电机基础知识列表
     */
    @GetMapping("/by-manufacturer")
    public ResponseEntity<List<AmKnowledgeBasicDto>> findByManufacturer(@RequestParam String manufacturer) {
        return ResponseEntity.ok(amKnowledgeBasicService.findByManufacturer(manufacturer));
    }
    
    /**
     * 根据额定功率范围查询
     *
     * @param minPower 最小功率
     * @param maxPower 最大功率
     * @return 符合条件的电机基础知识列表
     */
    @GetMapping("/by-power-range")
    public ResponseEntity<List<AmKnowledgeBasicDto>> findByRatedPowerRange(
            @RequestParam BigDecimal minPower,
            @RequestParam BigDecimal maxPower) {
        return ResponseEntity.ok(amKnowledgeBasicService.findByRatedPowerRange(minPower, maxPower));
    }
    
    /**
     * 根据额定电压范围查询
     *
     * @param minVoltage 最小电压
     * @param maxVoltage 最大电压
     * @return 符合条件的电机基础知识列表
     */
    @GetMapping("/by-voltage-range")
    public ResponseEntity<List<AmKnowledgeBasicDto>> findByRatedVoltageRange(
            @RequestParam BigDecimal minVoltage,
            @RequestParam BigDecimal maxVoltage) {
        return ResponseEntity.ok(amKnowledgeBasicService.findByRatedVoltageRange(minVoltage, maxVoltage));
    }
    
    /**
     * 统计某个生产厂商的电机数量
     *
     * @param manufacturer 制造商
     * @return 电机数量
     */
    @GetMapping("/count-by-manufacturer")
    public ResponseEntity<Long> countByManufacturer(@RequestParam String manufacturer) {
        return ResponseEntity.ok(amKnowledgeBasicService.countByManufacturer(manufacturer));
    }
} 